﻿<template>
  <div class="swiper" :style="{height: height}">
    <div class="swiper-inner">
      <div class="swiper-items" :style="styles">
        <slot></slot>
      </div>
      <button v-if="childLength>slides" :disabled="!activeIndex" @click="handlePrev" type="button" class="swiper-arrow swiper-arrow-left">
        <i class="el-icon-arrow-left"></i>
      </button>
      <button v-if="childLength>slides" :disabled="activeIndex > childLength - slides - 1" @click="handleNext" type="button" class="swiper-arrow swiper-arrow-right">
        <i class="el-icon-arrow-right"></i>
      </button>
    </div>
    <div class="swiper-nav" v-if="slides==1">
      <span 
        v-for="(item, index) in childLength"
        type="button"
        :class="index==activeIndex?'active':''"
        >
      </span>
    </div>
  </div>
</template>
<script>
  export default {
    componentName: 'ESwiper',
    props: {
      slides: {
        type: Number,
        default: 5
      },
      gutter: {
        type: Number,
        default: 10
      },
      height: {
        type: String,
        default: '150px'
      }
    },
    computed: {
      styles () {
        return {
          '-ms-transform': `translate(${-this.activeIndex * this.itemWidth}px,0)`,
          '-webkit-transform': `translate(${-this.activeIndex * this.itemWidth}px,0)`,
          'transform': `translate(${-this.activeIndex * this.itemWidth}px,0)`
        }
      }
    },
    data () {
      return {
        clientWidth: 0,
        itemWidth: 0,
        childLength: 0,
        childWidth: 0,
        activeIndex: 0
      }
    },
    mounted () {
      this.init()
    },
    updated () {
      this.init()
    },
    methods: {
      init () {
        this.clientWidth = this.$el.clientWidth
        this.childLength = this.$children.length
        this.childWidth = (this.clientWidth - (this.slides - 1) * this.gutter) / this.slides
        this.itemWidth = this.childWidth + this.gutter
      },
      transform (i) {
        this.activeIndex = this.activeIndex + i
      },
      handlePrev () {
        this.activeIndex > 0 && this.transform(-1)
      },
      handleNext () {
        this.activeIndex < this.childLength - this.slides && this.transform(1)
      },
      handleMouseEnter (index) {
        this.activeIndex = index
      }
    }
  }
</script>
